package com.sxit.ecwx.core.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.Map;
import java.util.Properties;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import freemarker.template.TemplateExceptionHandler;

/**
 * 公共帮助类
 * 
 * @author yubing
 *
 */
public class EcwxUtils {
	
	
	/**
	 * 模板引擎，生成html5静态模板
	 * 
	 * @param data 数据模型
	 * @param fmarkerDirPath 模板目录路径
	 * @param templateName 引用模板名称
	 * @param targetPath 输出文件完整路径
	 */
	public static boolean buildModelHtml5(Map<String, Object> data, String fmarkerDirPath,String templateName, String targetPath){
		Configuration cfg = new Configuration();
		boolean result=false;
		try {
			cfg.setDefaultEncoding("UTF-8");
			// 加载模板文件
			cfg.setDirectoryForTemplateLoading(new File(fmarkerDirPath));
			cfg.setTemplateExceptionHandler(TemplateExceptionHandler.IGNORE_HANDLER);
			Template template = cfg.getTemplate(templateName);
			template.setEncoding("UTF-8");
			Writer out = new OutputStreamWriter(new FileOutputStream(targetPath),"UTF-8");
			template.process(data, out);
			result=true;
		} catch (IOException e) {
			System.out.println("logError:EcwxUtils buildModelHtml5 occur error 1. "+e.getMessage());
		} catch (TemplateException e) {
			System.out.println("logError:EcwxUtils buildModelHtml5 occur error 2. "+e.getMessage());
		}
		return result;
	}
	
	/**
	 * 读取属性文件值
	 * 
	 * @param key
	 * @param configFileName
	 * @return
	 */
	public static String readPropertiesValue(String key,String configFileName){
		Properties p = new Properties();
		try {
			InputStream profile = Thread.currentThread().getContextClassLoader().getResourceAsStream(configFileName);
			p.load(profile);
			String value = p.getProperty(key);
			profile.close();
			return value;
		} catch (Exception e) {
			System.out.println(">>>>key&configFileName:"+key+"&"+configFileName);
			System.out.println("logError:EcwxUtils readPropertiesValue occur error. "+e.getMessage());
			return null;
		}
	}
}
